package com.kaussoft.lolblog.util;

import org.apache.log4j.Logger;
import org.codehaus.xfire.MessageContext;
import org.codehaus.xfire.exchange.InMessage;
import org.codehaus.xfire.fault.XFireFault;
import org.codehaus.xfire.handler.AbstractHandler;
import org.jdom.Element;
import org.jdom.Namespace;


/**
 * XFire的回调的Handler,在XFire配置文件中配置Server端的认证模块.
 * <p/>
 * ClientAuthHandler跟AuthenticationHandler要一起用,或者都不用.
 *
 * @author david.turing(openssl.blogjava.net)
 * @see ClientAuthHandler
 */
public class AuthenticationHandler extends AbstractHandler {
	private static final Logger log = Logger.getLogger(AuthenticationHandler.class);

	public void invoke(MessageContext context) throws Exception {

		log.info("#AuthenticationHandler is invoked");
		InMessage message = context.getInMessage();

		Namespace tokenNS = Namespace.getNamespace("springside", "http://xfire.components.bookstore.springside.org");

		if (message.getHeader() == null) {
			throw new XFireFault("GetRelation Service Should be Authenticated", XFireFault.SENDER);
		}

		Element token = message.getHeader().getChild("AuthenticationToken", tokenNS);
		if (token == null) {
			throw new XFireFault("Request must include authentication token.", XFireFault.SENDER);
		}

		String username = token.getChild("Username", tokenNS).getValue();
		String password = token.getChild("Password", tokenNS).getValue();

		if (username == null || password == null)
			throw new XFireFault("Supplied Username and Password Please", XFireFault.SENDER);

		//调用PasswordAuthenticationManager检查用户名密码是否正确
		//PasswordAuthenticationManager pamanager = new PasswordAuthenticationManager();
		//if (!pamanager.authenticate(username, password))
		//	throw new XFireFault("Authentication Fail! Check username/password", XFireFault.SENDER);
	}
}

